<?php
namespace app\middleware;

use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;
use Tinywan\Jwt\JwtToken;

class AdminJwtMiddleware implements MiddlewareInterface
{
    public function process(Request $request, callable $handler): Response
    {
        try {
            $token = $request->header('Authorization');
            if (!$token) {
                throw new \Exception('缺少 Authorization Token');
            }
            
            $jwt = JwtToken::getInstance();
            $payload = $jwt->verify($token);
            
            // 验证是否为后台用户
            if (!isset($payload['type']) || $payload['type'] !== 'admin') {
                throw new \Exception('无效的管理员权限');
            }
            
            $request->user = $payload;
            
            return $handler($request);
        } catch (\Exception $e) {
            return json([
                'code' => 401,
                'msg' => $e->getMessage()
            ]);
        }
    }
} 